package com.example.myapp.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.example.myapp.C;
import com.example.myapp.R;
import com.example.myapp.chat.ChatManager;

public class MyActivity extends Activity{

    private EditText etSendContent;

    private BroadcastReceiver receiveMsgBr = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String refreshListAction = intent.getAction();
            Log.d(C.LOG, "br received:" + refreshListAction);
            if (refreshListAction.equals(C.BR_RECEIVE_MSG)) {
                appendToUI(intent.getStringExtra("data"));
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initBrs();

        setContentView(R.layout.main);
        etSendContent = (EditText)findViewById(R.id.etSendContent);
     }

    private void initBrs() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(C.BR_RECEIVE_MSG);
        if(receiveMsgBr != null) {
            registerReceiver(receiveMsgBr, intentFilter);
        }
    }

    public void initChat(View view) {
        String c = etSendContent.getEditableText().toString();
        ChatManager.getInstance().sendMsg("1", c);
        appendToUI(c);
    }

    private void appendToUI(String str){
        String str2 = etSendContent.getText().toString();
        str2 = str2 +"\r\n"+str;
        etSendContent.setText(str2);
    }

}
